package com.example.demo.core.util;


import com.example.demo.core.exception.NotFoundException;
import com.example.demo.core.exception.ProgramException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.filechooser.FileFilter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * @author yj
 * @date 2021/3/26 14:14
 */
public class FileIOUtil {

    public static InputStream filePathToFileInputStream(String path) {
        try {
            return new FileInputStream(path);
        } catch (FileNotFoundException e) {
            throw new NotFoundException("指定路径文件没找到");
        }
    }

    public static OutputStream filePathToFileOutputStream(String path) {
        try {
            return new FileOutputStream(path);
        } catch (FileNotFoundException e) {
            throw new NotFoundException("指定路径文件没找到");
        }
    }

    /**
     * 拷贝文件
     *
     * @param sourceFilePath 源文件地址
     * @param sourceFileName 源文件名
     * @param targetFilePath 目标文件地址
     * @param targetFileName 目标文件名
     */
    public static boolean copyFile(String sourceFilePath, String sourceFileName, String targetFilePath, String targetFileName) {
        File sourceFile = new File(sourceFilePath + sourceFileName);
        File targetFile = new File(targetFilePath + targetFileName);
        if (sourceFile.isDirectory()) {
            throw new ProgramException("只能拷贝文件");
        }
        try {
            InputStream inputStream = new FileInputStream(sourceFile);
            OutputStream outputStream = new FileOutputStream(targetFile);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            inputStream.close();
            outputStream.close();
            return true;
        } catch (FileNotFoundException e) {
            throw new NotFoundException("文件不存在");
        } catch (IOException e) {
            throw new ProgramException("文件不存在");
        }
    }

    /**
     * 判断指定的文件是否存在。
     *
     * @param fileName 要判断的文件的文件名
     * @return 存在时返回true，否则返回false。
     * @since 1.0
     */
    public static boolean existsFile(String fileName) {
        return new File(fileName).isFile();
    }

}